import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';

@Injectable()
export class UsersService {
  private readonly logger = new Logger(UsersService.name);

  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: number) {
    return this.usersRepository.findOne({ where: { userId: id } });
  }

  async findByUsername(username: string) {
    this.logger.debug(`Finding user by username: ${username}`);
    const user = await this.usersRepository.findOne({
      where: { username },
      // select: {
      //   userId: true,
      //   username: true,
      //   email: true,
      //   isAdmin: true,
      //   password: true,
      // },
    });

    if (user) {
      this.logger.debug(
        `User found: ${JSON.stringify({ id: user.userId, username: user.username })}`,
      );
    } else {
      this.logger.debug(`User not found: ${username}`);
    }

    return user;
  }

  async create(user: Partial<User>): Promise<User> {
    const newUser = this.usersRepository.create(user);
    return this.usersRepository.save(newUser);
  }

  async update(id: number, user: Partial<User>): Promise<void> {
    await this.usersRepository.update(id, user);
  }

  async remove(id: number): Promise<void> {
    await this.usersRepository.delete(id);
  }
}
